import { type Graph, Point } from '@antv/x6'

class KeywordsEvent {

  private _graph: Graph

  constructor(graph: Graph) {
    this._graph = graph
    this._graph.bindKey('up', (e: KeyboardEvent) => {
      this.bindMove(e, ({ x, y }) => ({ x, y: y - 1 }))
    })
    this._graph.bindKey('down', (e: KeyboardEvent) => {
      this.bindMove(e, ({ x, y }) => ({ x, y: y + 1 }))
    })
    this._graph.bindKey('right', (e: KeyboardEvent) => {
      this.bindMove(e, ({ x, y }) => ({ x: x + 1, y }))
    })
    this._graph.bindKey('left', (e: KeyboardEvent) => {
      this.bindMove(e, ({ x, y }) => ({ x: x - 1, y }))
    })
  }


  private bindMove(e: KeyboardEvent, func: (point: Point.PointLike) => Point.PointLike) {
    if (this._graph.isSelectionEmpty()) {
      return false
    }
    this._graph.getSelectedCells().forEach((cell) => {
      if (cell.isNode()) {
        const { x, y } = func(cell.position())
        cell.position(Math.round(x), Math.round(y), { deep: true })
      }
    })
  }
}

export default KeywordsEvent
